<template>
  <div class="warpper">
    <div class="nav">
      <van-icon @click="this.$router.back(1)" color="#fff" size="30" name="arrow-left" />
      <div class="song-name">{{ songName }}</div>
    </div>
    <audio ref="audio" hidden="true" @pause="onPause" @play="onPlay" @timeupdate="onTimeupdate" @loadedmetadata="onLoadedmetadata" :src="songInfo.url" controls="controls"></audio>
    <div class="lyric-box">
      <ul ref="lyricUL" class="lyric">
        <li v-for="(item, i) in lyricsObjArr" :style="{ color: lyricIndex == i ? 'skyblue' : '#ded9d9' }" :key="item.uid" :data-index="i" ref="lyric">{{ item.lyric }}</li>
      </ul>
    </div>
    <div class="audio-controller">
      <div class="revious-song">
        <i class="iconfont icon-shangyishoushangyige"></i>
      </div>
      <div class="pause-or-play">
        <!-- 暂停 -->
        <van-icon size="40" @click="onPause" v-show="audio.playing" name="pause-circle" />
        <!-- 播放 -->
        <van-icon size="40" @click="onPlay" v-show="!audio.playing" name="play-circle" />
      </div>
      <div class="next-song">
        <i class="iconfont icon-xiayigexiayishou"></i>
      </div>
    </div>
  </div>
</template>

<script>
import { songUrl, lyric } from '@/api/defaultApi.js'

function realFormatSecond(second) {
  var secondType = typeof second

  if (secondType === 'number' || secondType === 'string') {
    second = parseInt(second)

    var hours = Math.floor(second / 3600)
    second = second - hours * 3600
    var mimute = Math.floor(second / 60)
    second = second - mimute * 60

    return hours + ':' + ('0' + mimute).slice(-2) + ':' + ('0' + second).slice(-2)
  } else {
    return '0:00:00'
  }
}
export default {
  data() {
    return {
      songId: '',
      songName: '',
      lyric: '', //歌词
      songInfo: {},
      lyricsObjArr: [],
      lyricIndex: 0,
      audio: {
        // 该字段是音频是否处于播放状态的属性
        playing: true,
        // 音频当前播放时长
        currentTime: 0,
        // 音频最大播放时长
        maxTime: 0,
      },
    }
  },
  filters: {
    // 使用组件过滤器来动态改变按钮的显示
    transPlayPause(value) {
      return value ? '暂停' : '播放'
    },
    // 将整数转化成时分秒
    formatSecond(second = 0) {
      return realFormatSecond(second)
    },
  },
  created() {
    if (!this.songId) {
      this.audio.playing = false
    }
    //拿到歌曲id
    this.songId = this.$route.query.id
    this.songName = this.$route.query.name
  },

  mounted() {
    this.getSongUrl()
    this.getLyric()
    this.play()
  },
  methods: {
    getSongUrl() {
      songUrl({ id: this.songId }).then((res) => {
        this.songInfo = res.data.data[0]
      })
    },
    getLyric() {
      lyric({ id: this.songId }).then((res) => {
        this.lyric = res.data.lrc.lyric

        this.initLyric()
      })
    },
    //初始化歌词
    initLyric() {
      const regNewLine = /\n/
      const lineArr = this.lyric.split(regNewLine) // 每行歌词的数组
      const regTime = /\[\d{2}:\d{2}.\d{2,3}\]/
      lineArr.forEach((item) => {
        if (item === '') return
        const obj = {}
        const time = item.match(regTime)

        obj.lyric = item.split(']')[1].trim() === '' ? '' : item.split(']')[1].trim()
        obj.time = time ? this.formatLyricTime(time[0].slice(1, time[0].length - 1)) : 0
        obj.uid = Math.random().toString().slice(-6)
        if (obj.lyric === '') {
          //   console.log('这一行没有歌词')
        } else {
          this.lyricsObjArr.push(obj)
        }
      })
    },
    formatLyricTime(time) {
      // 格式化歌词的时间 转换成 sss:ms
      const regMin = /.*:/
      const regSec = /:.*\./
      const regMs = /\./

      const min = parseInt(time.match(regMin)[0].slice(0, 2))
      let sec = parseInt(time.match(regSec)[0].slice(1, 3))
      const ms = time.slice(time.match(regMs).index + 1, time.match(regMs).index + 3)
      if (min !== 0) {
        sec += min * 60
      }
      return Number(sec + '.' + ms)
    },
    // 控制音频的播放与暂停
    startPlayOrPause() {
      return this.audio.playing ? this.pause() : this.play()
    },
    // 播放音频
    play() {
      this.$refs.audio.play()
    },
    // 暂停音频
    pause() {
      this.$refs.audio.pause()
    },
    // 当音频播放
    onPlay() {
      this.audio.playing = true
      this.$refs.audio.play()
    },
    // 当音频暂停
    onPause() {
      this.audio.playing = false
      this.$refs.audio.pause()
    },
    // 当timeupdate事件大概每秒一次，用来更新音频流的当前播放时间
    onTimeupdate(res) {
      this.audio.currentTime = res.target.currentTime
      for (let i = 0; i < this.lyricsObjArr.length; i++) {
        if (this.audio.currentTime > parseInt(this.lyricsObjArr[i].time)) {
          const index = this.$refs.lyric[i].dataset.index
          if (i === parseInt(index)) {
            this.lyricIndex = i
            this.$refs.lyricUL.style.transform = `translateY(${170 - 25 * (i + 1)}px)`
          }
        }
      }
    },
    // 当加载语音流元数据完成后，会触发该事件的回调函数
    // 语音元数据主要是语音的长度之类的数据
    onLoadedmetadata(res) {
      //   console.log('loadedmetadata')
      this.audio.maxTime = parseInt(res.target.duration)
    },
  },
}
</script>

<style lang="less" scoped>
.warpper {
  width: calc(100%);
  min-height: calc(100vh);
  //   padding: 10px;
  background: #36d1dc; /* fallback for old browsers */
  background: -webkit-linear-gradient(to right, #5b86e5, #36d1dc); /* Chrome 10-25, Safari 5.1-6 */
  background: linear-gradient(to right, #5b86e5, #36d1dc); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}
.lyric-box {
  width: 100%;
  height: 15rem;
  overflow-y: scroll;

  .lyric {
    padding-top: 7rem;
    padding-bottom: 3rem;
    width: 100%;
    font-size: 16px;
    li {
      line-height: 150%;
      display: flex;
      justify-content: center;
    }
  }
}
.nav {
  //   position: fixed;
  width: calc(100% - 30px);
  background: rgba(255, 255, 255, 0.3);
  display: flex;
  align-items: center;
  padding: 10px 15px;
  .song-name {
    font-size: 16px;
    margin: auto;
  }
}
.audio-controller {
  width: 70%;
  height: 60px;
  background: rgba(255, 255, 255, 0.8);
  position: fixed;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 20px;
}
.revious-song,
.next-song {
  width: 60px;
  text-align: center;
}
.iconfont {
  font-size: 38px;
}
</style>